import 'dart:typed_data';

import 'package:dio/dio.dart' as mDio;
import 'package:flutter_module/common/base/logic/BasicLogic.dart';
import 'package:flutter_module/common/http/ApiConstant.dart';
import 'package:flutter_module/common/http/YZHttpUtils.dart';
import 'package:flutter_module/common/http/exception/AppException.dart';
import 'package:flutter_module/common/utils/photo_selector_util.dart';
import 'package:flutter_module/model/Result_bool.dart';
import 'package:flutter_module/model/Update_file.dart';
import 'package:flutter_module/model/book.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';

import '../../../common/third/analytics/YZAnalytics.dart';
import '../../../common/utils/DateSelectorUtil.dart';

class AddBookLogic extends BasicLogic {
  var bookName = '';
  var bookAuthor = '';
  var imageFileName = "";
  var imageOssUrl = "";
  Rx<Uint8List?> localImageByte = Uint8List(0).obs;
  var bookNameController = TextEditingController();
  var bookAuthorController = TextEditingController();
  var bookPressController = TextEditingController();
  var bookPressDateController = TextEditingController();
  var bookIsbnController = TextEditingController();
  RegExp regexp = RegExp(
      "[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]");

  @override
  void onInit() {
    super.onInit();
    YZAnalytics.track("D00007", "查找书籍页-添加书籍", "读书笔记", null);
  }

  void setParameter(String bookName) {
    bookName = bookName;
    bookNameController.text = bookName;
  }

  //书籍选择
  void takePotato() {
    PhotoSelectorUtil().showPhotoSelector(
      callback: (image, fileName, byte) {
        imageFileName = fileName;
        localImageByte.value = byte;
        PhotoSelectorUtil().removeListener?.call();
      },
    );
  }

  void updateLocalImg(Uint8List byte, String fileName,
      Function(dynamic data) updateLocalSuccessAction) async {
    HttpUtils.upload(
        api_upload_image,
        mDio.FormData.fromMap({
          "file": await mDio.MultipartFile.fromBytes(byte, filename: fileName),
        }),
        onSendProgress: (int1, int2) {}, successCallBack: (data, total) {
      updateLocalSuccessAction(data);
    }, errorCallBack: (e) {
      SmartDialog.dismiss();
      AppException err = e as AppException;
      SmartDialog.showToast(err.getMessage());
    });
  }

  void validContext(Function(dynamic data) validSuccessAction) {
    HttpUtils.post(api_valid_context, data: {"context": getAllContent()},
        successCallBack: (data, total) {
      validSuccessAction(data);
    }, errorCallBack: (e) {
      SmartDialog.dismiss();
      AppException err = e as AppException;
      SmartDialog.showToast(err.getMessage());
    });
  }

  String getAllContent() {
    return "${bookAuthorController.text}${bookNameController.text}"
        "${bookPressController.text}${bookIsbnController.text}";
  }

  bool checkCommitEnable() {
    bookName = bookNameController.text;
    bookAuthor = bookAuthorController.text;
    if (localImageByte.value?.isBlank ?? true) {
      SmartDialog.showToast('请上传书籍封面');
      return false;
    } else if (bookName.isEmpty) {
      SmartDialog.showToast("请输入书籍名");
      return false;
    } else if (bookAuthor.isEmpty) {
      SmartDialog.showToast("请输入书籍作者");
      return false;
    } else {
      return true;
    }
  }

  void commit(BuildContext context) {
    FocusScope.of(context).requestFocus(FocusNode());
    //必传字段判断
    if (!checkCommitEnable() || localImageByte.value == null) {
      return;
    }
    SmartDialog.showLoading();
    updateLocalImg(localImageByte.value!, imageFileName, (data) {
      UpdateFile updateFile = UpdateFile.fromJson(data);
      if (updateFile.url.isBlank == false) {
        imageOssUrl = updateFile.url ?? "";

        ///敏感词校验
        validContext((date) {
          print("validContext->>>>$data");
          ResultBool resultBool = ResultBool.fromJson(date);
          if (resultBool.result == true) {
            postCommitBookInfo((data) {
              SmartDialog.dismiss();
              Book book = Book.fromJson(data);
              if (book.bookId.isBlank != true) {
                book.bookCover = imageOssUrl;
                book.bookTitle = bookNameController.text;
                BoostNavigator.instance.pop(book);
              }
            });
          } else {
            SmartDialog.dismiss();
            SmartDialog.showToast("内容包含不合适的字符，请修改后再提交");
          }
        });
      } else {
        SmartDialog.dismiss();
        SmartDialog.showToast("上传失败");
      }
    });
  }

  ///添加书籍请求
  void postCommitBookInfo(Function(dynamic date) bookAddSuccessAction) {
    HttpUtils.post(api_book_add, data: {
      ///图书作者
      'bookAuthor': bookAuthorController.text,

      ///图书封面
      'bookCover': imageOssUrl,

      ///ISBN
      'bookIsbn': bookIsbnController.text,

      ///bookPress
      'bookPress': bookPressController.text,

      ///出版年份
      'bookPublicationYear': bookPressDateController.text,

      ///图书名称
      'bookTitle': bookNameController.text,
    }, successCallBack: (data, total) {
      bookAddSuccessAction(data);
    }, errorCallBack: (e) {
      SmartDialog.dismiss();
      AppException err = e as AppException;
      SmartDialog.showToast(err.getMessage());
      // BoostNavigator.instance.pop(  Book(bookId: 121,bookCover: state.imageOssUrl,));
    });
  }

//时间选择
  void showDateSelector(BuildContext context) {
    FocusScope.of(context).requestFocus(FocusNode());
    DateSelectorUtil.showDateSelector(context, onConfirm: (date) {
      var year = date.year;
      var month = date.month;
      var day = date.day;
      bookPressDateController.text = '$year-$month-$day';
    });
  }
}
